<template>
  <div class="qrcode-list-container" v-loading.fullscreen.lock="loading">
    <!--搜索-->
    <div ref="tableHeaderContainer" class="qrcode-list-search-group-container list-search-group-container">
      <el-radio-group v-model="params.state" @change="stateChange" class="flex-1">
        <el-radio-button label="">{{ $t('common.base.all') }}</el-radio-button>
        <el-tooltip placement="top" :content="$t('product.qrcode.tips.tip1')">
          <el-radio-button label="1">
            {{ $t('common.base.associated') }}
          </el-radio-button>
        </el-tooltip>
        <el-tooltip placement="top" :content="$t('product.qrcode.tips.tip2')">
          <el-radio-button label="0">
            {{ $t('common.base.notContact') }}
          </el-radio-button>
        </el-tooltip>
        <el-tooltip placement="top" :content="$t('product.qrcode.tips.tip3')">
          <el-radio-button label="3">
            {{ $t('product.qrcode.text.text1') }}
          </el-radio-button>
        </el-tooltip>
      </el-radio-group>
      <form class="base-search" onsubmit="return false;">
        <div class="qrcode-list-base-search-group base-search-group input-with-append-search">
          <el-input
            v-model="params.keyword"
            :placeholder="$t('product.qrcode.placeholder.keyword')"
            class="task-mr12"
            v-trim:blur>
            <i slot="prefix" class="el-input__icon el-icon-search"></i>

            <el-button
              type="primary"
              slot="append"
              @click="params.pageNum=1;search();trackEventHandler('search')"
              v-track="$track.formatParams('KEYWORD_SEARCH')"
              native-type="submit">
              {{ $t('common.base.search') }}
            </el-button>
          </el-input>
          <el-button
            type="plain-third"
            v-track="$track.formatParams('RESET_SEARCH')"
            @click="resetParams">
            {{ $t('common.base.reset') }}
          </el-button>
        </div>
        <span class="advanced-search-visible-btn" @click.self.stop="advanceSearch">
          <i class="iconfont icon-filter"></i>
          {{ $t('component.advancedSearch.title') }}
        </span>
      </form>
    </div>

    <!--list start-->
    <div class="qrcode-list-component">
      <!--operation bar start-->
      <div ref="tableDoContainer" class="operation-bar-container">
        <div class="top-btn-group">
          <el-button
            v-if="canProductCodeCreate"
            type="primary"
            size="small"
            @click="createQrcode"
            v-track="$track.formatParams('CREATE_QRCODE')"
            style="margin-left:0;">
            {{ $t('product.createQrcode') }}
          </el-button>
          <el-button
            v-if="canProductCodeDownload"
            type="primary"
            size="small"
            @click="download"
            v-track="$track.formatParams('DOWNLOAD_QRCODE')"
          >
            {{ $t('product.downloadQrcode') }}
          </el-button>
          <el-dropdown @command="handleCommand" v-if="!isExperienceEdition && canProductCodeProduct">
            <el-button
              type="primary"
              size="small"
            >
              {{ $t('product.relateProduct') }}
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command='associate' v-track="$track.formatParams('BATCH_PRODUCT_RELATE')">{{ $t('product.qrcode.btns.btn2') }}</el-dropdown-item>
              <el-dropdown-item command='update' v-track="$track.formatParams('BATCH_PRODUCT_UPDATE')">{{ $t('product.qrcode.btns.btn3') }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <el-button
            type="plain-third"
            v-if="qrcodePermission && canProductCodeDelete"
            v-track="$track.formatParams('DELETE')"
            @click="deleteCodeMul">
            <i class="iconfont icon-delete" ></i>{{ $t('common.base.delete') }}
          </el-button>
        </div>

        <div class="action-button-group">
          <a :href="help_link" style="color:#576B95;" target="_blank">
            <i class="iconfont icon-book"></i>
            {{ $t('product.qrcode.btns.btn4') }}
          </a>
          <el-dropdown trigger="hover">
            <span class="el-dropdown-link cur-point" v-if="exportPermission && isButtonDisplayed">
              {{ $t('common.base.moreOperator') }}
              <i class="iconfont icon-fdn-select"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportQrcode(false)" v-track="$track.formatParams('EXPORT', null, 'MORE_ACTIONS')">{{ $t('common.base.export') }}</div>
              </el-dropdown-item>
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="exportQrcode(true)" v-track="$track.formatParams('EXPORT_ALL', null, 'MORE_ACTIONS')">{{ $t('common.base.exportAll') }}</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!--operation bar end-->

      <el-table
        v-table-style
        :data="tableData"
        stripe
        border
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        :height="tableContainerHeight"
        :highlight-current-row="false"
        header-row-class-name="qrcode-table-header"
        cell-class-name='qrcode-table-cell'
        ref="multipleTable"
        class="qrcode-table bbx-normal-list-box"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
        </template>
        <el-table-column type="selection" width="48" align="center" class-name="select-column"></el-table-column>
        <el-table-column
          v-for="(column, index) in columns"
          v-if="column.show"
          :key="`${column.field}_${index}`"
          show-overflow-tooltip
          :label="column.label"
          :prop="column.field"
          :width="column.width"
          :min-width="column.minWidth || '120px'"
          :class-name="column.field == 'name' ? 'customer-name-superscript-td' : ''"
          :sortable="column.sortable"
          :align="column.align"
          :fixed="column.fixLeft || column.fixed || false"
        >
          <template slot-scope="scope">
            <template v-if="column.field === 'state'">
              {{getState(scope.row)}}
            </template>
            <template v-else-if="column.field === 'productName'">
              <div 
                class="table-pointer"
                @click="toProductDetail(scope.row.productId)" 
                :class="globalIsHaveProductViewDetailAuth ? 'operate-primary' : 'operate-disabled'"
              >
                {{scope.row[column.field]}}
              </div>
            </template>
            <!-- 关联人 -->
            <template v-else-if="column.field === 'relatedPersons'">
              <template v-if="isOpenData && scope.row.simpleUserVO && scope.row.simpleUserVO.staffId">
                <open-data type="userName" :openid="scope.row.simpleUserVO.staffId"></open-data>
              </template>
              <template v-else>
                {{ scope.row.simpleUserVO && scope.row.simpleUserVO.displayName }}
              </template>
            </template>
            <!-- 下载状态  -->
            <template v-else-if="column.field === 'downloads'">
              {{ scope.row.downloads == 1 ? $t('product.hasDownloaded') : $t('common.base.notDownloaded')}}
            </template>
            <template v-else-if="column.field === 'operation'">
              <el-dropdown class="dropdown" v-if="canProductCodeProduct && ((!scope.row.productId && scope.row.available===1) || scope.row.productId)">
                <span class="cur-point">
                  {{$t('common.base.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" class="lang-select-dropdown">
                  <el-dropdown-item><div @click="preview(scope.row)">{{ $t('common.base.preview') }}</div></el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="associateSingle(scope.row.qrcodeId)" v-if="!scope.row.productId && scope.row.available===1">{{ $t('product.relateProduct') }}</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div @click="unbindQrcode(scope.row)" v-if="scope.row.productId">{{ $t('common.base.disassociate') }}</div>
                  </el-dropdown-item>
                  <el-dropdown-item>
                    <div v-if="isReportAuth && scope.row.productId" type="text" @click="goQrcode(scope.row.qrcodeId)">{{ $t('product.qrcode.btns.btn5') }}</div>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

              <div v-else>
                <el-button type="text" class="operate-primary" @click="preview(scope.row)">{{ $t('common.base.preview') }}</el-button>
              </div>
              
              <!-- <el-button type='text' class="operate-danger" @click="deleteCode(scope.row)">删除</el-button> -->
            </template>
            <template v-else>{{scope.row[column.field]}}</template>
          </template>
        </el-table-column>
      </el-table>
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-10">
        <div class="list-info">
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ totalItems }}</span>
          </i18n>
          <template v-if="multipleSelection&&multipleSelection.length>0">
            <i18n path="common.base.table.selectedNth">
              <span place="count" class="color-primary pad-l-5 pad-r-5" @click="multipleSelectionPanelShow = true">{{ multipleSelection.length }}</span>
            </i18n>
            <span class="customer-selected-count" @click="toggleSelection()">{{$t('common.base.clear')}}</span>
          </template>
        </div>
        <el-pagination
          class="customer-table-pagination"
          background
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="params.pageSize"
          :current-page="params.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="totalItems"
        ></el-pagination>
      </div>
    </div>
    <!-- list end -->

    <qrcode-search-form ref="qrcodeSearchForm" @search='search' @resetParams='resetParams' @input='searchInput'></qrcode-search-form>

    <qrcode-dialog ref="previewDialog" @createCode='createCode' :init-data='initData' :dialog-type='dialogType' :qrcode-data='qrcodeData' :allow-qr-code-import="allowQrCodeImport"></qrcode-dialog>
    <new-qrcode-dialog ref="newQrcodeDialog" @createCode="createCode" :init-data="initData" :qrcode-data="qrcodeData"></new-qrcode-dialog>

    <associate-dialog ref="associateDialog" :qrcode-id='qrcodeId' @success='createCode'></associate-dialog>

    <unbind-dialog ref="unbindDialog" @unbindSuc='search' :qrcode-id='qrcodeId' :product-id='productId' :auth="auths"></unbind-dialog>
    
    <!-- start 批量关联、更新 -->
    <base-import ref="importBatch" @success='batchSuc' :title="batchTitle" :tooltip='batchTooltip' :content='batchContent' :action="batchAction">
      <div slot="tip">
        <div>
          <batch-dialog ref="batchDialog" :multiple-selection='multipleSelection' :counts='batchCounts' :batch-type='batchType'></batch-dialog>
        </div>
      </div>
    </base-import>
    <!-- end 批量关联、更新 -->
  </div>
</template>

<script>
// pageDes 产品二维码列表
import * as producqQrcode from '@src/api/productQrcode';
import * as _ from 'lodash';
import Searchform from './component/SearchForm';
import QrcodeDialog from './component/QrcodeDialog';
import NewQrcodeDialog from './component/NewQrcodeDialog';
import AssociateDialog from './component/AssociateDialog';
import BatchDialog from './component/BatchDialog';
import UnbindDialog from './component/unbindDialog';
import { checkButtonDisplayed } from '@src/util/dom';
import { getRootWindowInitData } from '@src/util/window'
/* mixins */
import VersionMixin from '@src/mixins/versionMixin/index.ts'
import AuthMixin from '@src/mixins/authMixin'
import SuperQrCodeBhAnalysis from '@src/modules/productV2/bhAnalysis/grayMixins'

/* export & import */
// import { eventListExport } from '@src/api/Export';
import { superQrcodeImport_1, superQrcodeImport_2 } from '@src/api/Import';
import { storageSet, storageGet } from '@src/util/storageV2';
import { openAccurateTab, isOpenData } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getSystemNormalSearchInputForLength } from '@model/utils/getSystemConfig.ts'
import { defaultTableData } from '@src/util/table'
import { getRootWindow } from '@src/util/dom';

export default {
  name:'product-super-qrcode',
  inject:['initData'],
  mixins: [VersionMixin, AuthMixin, SuperQrCodeBhAnalysis],
  data(){
    return{
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      loading:true,
      params:{
        productId:'',
        qrcodeId:'',
        state:'',
        keyword:'',
        pageNum:1,
        pageSize:10
      },
      multipleSelectionPanelShow: false,
      multipleSelection: [],
      tableData:[],
      columns:this.buildColumns(),
      totalItems:0,
      qrcodeData:{},
      dialogType:'',
      selectedLimit: 500,
      qrcodeId:'',
      batchType:'',
      batchContent: this.$t('product.qrcode.tips.tip4', {count: 1000}),
      batchCounts:{},
      productId:'',
      tableContainerHeight:'440px',
      isOpenData,
    }
  },
  computed:{
    batchTitle(){
      return this.batchTyp === 'associate' ? this.$t('product.qrcode.btns.btn2') : this.$t('product.qrcode.btns.btn3')
    },
    batchTooltip(){
      return this.batchType !== 'associate'
    },
    batchAction(){
      return this.batchType === 'associate' ? superQrcodeImport_1 : superQrcodeImport_2
    },
    tenantType(){
      return getRootWindowInitData()?.tenantType
    },
    help_link(){
      let url = ''
      if(this.tenantType == 2) {
        url = 'https://docs.qq.com/doc/p/5ceb8f7e71db1762e60eda21cc2098e990f6e4ed?dver=2.1.27237808'
      } else if(this.tenantType == 4) {
        url = 'https://publink-hz.feishu.cn/wiki/wikcnQ8J1RsnfWOcMOMqBl9VI2g'
      } else {
        url = 'https://doc.shb.ltd/shb_xoqazk/ia4qctp2ly559d1m/wtr4x2a43al72qae/st8453y62ancq9ki.html'
      }
      return url
    },
    auths () {
      return this.initData?.auths
    },
    exportPermission () {
      return this.auths?.PRODUCT_CODE_EXPORT;
    },
    canProductCodeCreate() {
      return this.auths?.PRODUCT_CODE_CREATE
    },
    canProductCodeDownload() {
      return this.auths?.PRODUCT_CODE_DOWNLOAD
    },
    canProductCodeProduct() {
      return this.auths?.PRODUCT_CODE_PRODUCT
    },
    canProductCodeDelete() {
      return this.auths?.PRODUCT_CODE_DELETE
    },
    qrcodePermission () {
      return this.auths?.CUSTOMER_PQRCODE;
    },
    // 允许二维码导入和关联产品灰度
    qrCodeImportAndAutoRelationGray() {
      const RootWindow = getRootWindow(window)
      return RootWindow.grayAuth?.qrCodeImportAndAutoRelation || false;
    },
    // 允许二维码导入
    allowQrCodeImport() {
      return this.qrCodeImportAndAutoRelationGray && this.initData?.qrcodeEnabled && this.initData?.allowQrCodeImport == 'true';
    },
  },
  mounted(){
    if(!this.initData.qrcodeEnabled){
      this.$platform.alert(this.$t('product.qrcode.tips.tip5'));
    }
    this.revertStorage();
    this.columns = this.buildTableColumn();
    this.search();
    let that_ = this;
    // 监听切换后需要重新计算列表高度 后续可以用activated生命周期替换
    window.addEventListener('message', (event)=> {
      const {action, data} = event.data;
      if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    });
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight()
      }, 500)
    })
  },
  methods:{
    // renderHeader(h,{column,$index}){
    //   if($index===2){
    //     return (
    //       <div>
    //         {column.label}
    //         <el-tooltip effect='dark' content='可以在PC端或移动端查看产品信息时绑定二维码' placement='bottom'>
    //           <i class='iconfont icon-fdn-info'></i>
    //         </el-tooltip>
    //       </div>
    //     )
    //   }
    //   return h('span',column.label,{class:'cell'})
    // },
    // 排序

    // 查看行为分析
    goQrcode(qrcodeId){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_bhAnalysis_${qrcodeId}`,
      //   title: '超级二维码行为分析',
      //   close: true,
      //   url: `/product/bhAnalysis?qrcode=${qrcodeId}&noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductBhAnalysis,
        key: qrcodeId,
        params: `qrcode=${qrcodeId}&noHistory=1`,
        fromId
      })
    },
    sortChange(option){
      const { prop, order } = option;
      const sortedField = this.columns.find(sf => sf.field === prop) || {};
      this.params.orderDetail = {
        column: sortedField.fieldForSort || prop,
        isSystem:1,
        sequence:order === 'ascending' ? 'ASC' : 'DESC',
        type:'string'
      }
      this.search();
    },
    // 跳转到产品详情
    toProductDetail(productId){
      
      if (!this.globalIsHaveProductViewDetailAuth) return
      
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `product_view_${productId}`,
      //   title: '产品详情',
      //   close: true,
      //   url: `/customer/product/view/${productId}?noHistory=1`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProductView,
        key: productId,
        params: 'noHistory=1',
        fromId
      })
    },
    // 高级搜索
    advanceSearch(){
      this.$refs.qrcodeSearchForm.open();
    },
    // 批量关联/更新
    async handleCommand(command){
      try{
        if(command === 'update' && this.multipleSelection.length > 0){
          this.batchType = command;
          this.$refs.importBatch.open();
          return
        }
        let {code, result, message} = await producqQrcode.getUnbindCodeCount();
        if(code === 0){
          this.batchCounts = result;
          this.batchType = command;
          this.$refs.importBatch.open();
        }else{
          this.$message.error(message);
        }
      }catch(err){
        console.error(err);
      }
    },
    // 导入成功
    batchSuc(){
      this.resetParams();
    },
    // 取消关联
    unbindQrcode(row){
      this.productId = row.productId;
      this.qrcodeId = row.qrcodeId;
      this.$refs.unbindDialog.open();
    },
    // 删除
    deleteCode(row){
      this.$confirm(this.$t('product.qrcode.tips.tip6'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        const params = {
          qrcodeId:row.qrcodeId,
          productId:row.productId || ''
        }
        producqQrcode.unbindQrCode(params).then(res=>{
          const {status, message} = res;
          this.$message({
            type:status === 0 ? 'success' : 'error',
            message
          });
          if(status === 0) this.search();
        })
      }).catch(()=>{})
    },
    // 批量删除
    deleteCodeMul(){
      if(!this.multipleSelection.length) return this.$platform.alert(this.$t('product.qrcode.tips.tip7'));
      this.$confirm(this.$t('product.qrcode.tips.tip6'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning'
      }).then(()=>{
        const params = this.multipleSelection.map(item=>{
          return {
            qrcodeId:item.qrcodeId,
            productId:item.productId || ''
          }
        });
        producqQrcode.unbindQrCode(params).then(res=>{
          const {status, message} = res;
          this.$message({
            type:status === 0 ? 'success' : 'error',
            message
          });
          if(status === 0){
            this.toggleSelection();
            this.search();
          }
        })
      }).catch(()=>{})
    },
    // 生成二维码
    createCode(){
      this.search();
    },
    // 高级搜索
    searchInput(key, val){
      this.params[key] = val;
    },
    // 预览
    preview(row){
      this.qrcodeData = row;
      this.dialogType = '预览'
      this.$refs.previewDialog.open();
    },
    // 关联产品
    associateSingle(qrcodeId){
      this.qrcodeId = qrcodeId;
      this.$refs.associateDialog.open();
    },
    // 状态
    getState(row){
      if(row.productId){
        return this.$t('common.base.associated')
      }else if(row.available === 0){
        return this.$t('product.qrcode.text.text1')
      }
      return this.$t('common.base.notContact')
      
    },
    // 获取数据
    async search(){
      try{
        let params_ = _.cloneDeep(this.params);
        params_.keyword = getSystemNormalSearchInputForLength(params_.keyword)
        let {data, status, message} = await producqQrcode.getList(params_);
        this.loading = false;
        if(status === 0){
          this.tableData = data.list;
          this.totalItems = data.total;
          this.matchSelected();
        }else{
          this.$message.error(message);
        }
        this.$nextTick(() => {
          this.loading = false;
        })
      }catch(err){
        console.error(err);
      }
    },
    // 匹配选中的列
    matchSelected () {
      if (!this.multipleSelection.length) return;

      const selected = this.tableData.filter((c) => {
        if (this.multipleSelection.some((sc) => sc.id === c.id)) {
          this.multipleSelection = this.multipleSelection.filter(
            (sc) => sc.id !== c.id
          );
          this.multipleSelection.push(c);
          return c;
        }
      }) || [];

      this.$nextTick(() => {
        this.toggleSelection(selected);
      });
    },
    jump(pageNum) {
      this.params.pageNum = pageNum;
      this.search();
    },
    handleSizeChange(pageSize) {
      this.saveDataToStorage('pageSize', pageSize);
      this.params.pageNum = 1;
      this.params.pageSize = pageSize;
      this.search();
    },
    getLocalStorageData() {
      const dataStr = storageGet('qrcodeListData') || '{}';
      return JSON.parse(dataStr);
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet('qrcodeListData', JSON.stringify(data));
    },
    revertStorage() {
      const { pageSize } = this.getLocalStorageData();
      if (pageSize) {
        this.params.pageSize = pageSize;
      }
    },
    buildColumns(){
      return [
        {
          label: this.$t('product.type.qrcodeId'),
          field: 'qrcodeId',
          show: true,
          sortable: 'custom',
          minWidth: '150px'
        },
        {
          label: this.$t('product.qrcode.type.state'),
          field: 'state',
          show: true,
        },
        {
          label: this.$t('product.downState'),
          field: 'downloads',
          show: true,
        },
        {
          label: this.$t('product.relateProduct'),
          field: 'productName',
          show: true,
        },
        {
          label: this.$t('product.qrcode.type.productSN'),
          field: 'productSN',
          fieldForSort: 'product.serialNumber',
          show: true,
          sortable: 'custom'
        },
        {
          label: this.$t('product.qrcode.text.text49'),
          field: 'relatedPersons',
          show: true,
        },
        {
          label: this.$t('product.qrcode.text.text51'),
          field: 'qrCodeUrl',
          show: true,
        },
        {
          label: this.$t('common.fields.action.displayName'),
          field: 'operation',
          show: true,
          width: '120px',
          fixed: 'right',
        }
      ]
    },
    // 多选
    handleSelection(selection){
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter((ms) =>
        this.tableData.some((cs) => cs.id === ms.id)
      );

      let unSelected = this.tableData.filter((c) =>
        original.every((oc) => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach((row) => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
        return this.$platform.alert(this.$t('common.base.tip.choiceLimit', {limit: this.selectedLimit}));
      }

      this.multipleSelection = tv;
    },
    // 计算已选择
    selectionCompute (selection) {
      let tv = [];

      tv = this.multipleSelection.filter((ms) =>
        this.tableData.every((c) => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    // 清空多选
    toggleSelection(rows){
      let isNotOnCurrentPage = false;
      let row = undefined;

      if (rows) {
        for (let i = 0; i < rows.length; i++) {
          row = rows[i];
          isNotOnCurrentPage = this.tableData.every((item) => {
            return item.id !== row.id;
          });
          if (isNotOnCurrentPage) return;
        }
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
        this.multipleSelection = [];
      }
    },
    // 选择状态
    stateChange(){
      this.params.pageNum = 1;
      this.search();
    },
    // 生成二维码
    createQrcode(){
      this.qrcodeData = {};
      this.dialogType = '生成';
      if (this.allowQrCodeImport) {
        this.$refs.newQrcodeDialog.open();
      } else {
        this.$refs.previewDialog.open();
      }
    },
    // 下载二维码
    download(){
      if(this.multipleSelection.length === 0){
        return this.$message.warning(this.$t('product.tips.selectDataTip'));
      }
      this.qrcodeData = this.multipleSelection;
      this.dialogType = '下载';
      this.$refs.previewDialog.open();
    },
    // 重置
    resetParams(){
      this.params = {
        productId:'',
        state:'',
        keyword:'',
        pageNum:1,
        pageSize:10
      }
      this.$refs.qrcodeSearchForm.reset();
      this.search();
    },
    // 导出
    async exportQrcode(all){
      if(this.params.state == 3){
        return this.$platform.alert(this.$t('product.qrcode.tips.tip8'));
      }
      if(!all && !this.multipleSelection.length){
        return this.$platform.alert(this.$t('product.qrcode.tips.tip9'));
      }
      let params;
      if(all){
        params = {
          smStr:`{"state":${this.params.state || '2'}}`
        }
      }else{
        params = {
          ids:this.multipleSelection.map(item=>item.id).join(',')
        }
      }
      try{
        let {status, message} = await producqQrcode.exportProductQrcode(params);
        this.$message({
          type:`${status === 0 ? 'success' : 'error'}`,
          message
        });
        // this.$platform.alert(message);
        if(status === 0){
          window.parent.showExportList();
          window.parent.exportPopoverToggle(true);
        }
      }catch(err){
        console.error(err);
      }
    },
    // TalkingData事件埋点
    trackEventHandler(type) {
      if (type === 'search') {
        window.TDAPP.onEvent('pc：产品二维码管理-搜索事件');
        return;
      }
      if (type === 'moreAction') {
        window.TDAPP.onEvent('pc：客户管理-更多操作事件');
        return;
      }
    },

    /**
     * @des 表单拖拽钩子函数
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (
            item.fieldName === column.property
            || item.field === column.property
          ) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },
    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },
    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null

      // 判断是否存储选择列
      const columnsList = this.columns.map(c => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft: c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },
    // 构建表格列
    buildTableColumn() {
      let baseColumns = this.buildColumns();
      const localStorageData = this.getLocalStorageData();
      let columnStatus = (localStorageData.columnStatus) || [];
      let localColumns = columnStatus
        .map(i => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col) => (acc[col.field] = col) && acc, {});
      let columns = [...baseColumns].map(col => {
        let { width, show } = col;
        let localField = localColumns[col.field];
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          width = typeof localField.width == 'number'
            ? `${localField.width}px`
            : `${localField.width}`.indexOf('px') ? localField.width : '';
          show = localField.show !== false;
        }
        col.show = show;
        col.width = width;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      if (this.isBasicEditionHideProduct) {
        columns = columns.filter(item => item.field !== 'esProductEntities')
      }

      return columns;
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
		 knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1  - 24 - 12;
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
  },
  components:{
    [Searchform.name]:Searchform,
    [QrcodeDialog.name]:QrcodeDialog,
    [NewQrcodeDialog.name]: NewQrcodeDialog,
    [AssociateDialog.name]:AssociateDialog,
    [BatchDialog.name]:BatchDialog,
    [UnbindDialog.name]:UnbindDialog
  }
}
</script>

<style lang="scss">
.el-select-dropdown__item.selected{
  span{
    color: $color-primary;
  }
}
</style>
<style lang="scss" scoped>
::v-deep .base-import-title{
  font-weight: bold;
}
::v-deep .el-table__row{
  td:not(.is-hidden):last-child{
    border-left:1px solid #EBEEF5; // 颜色根据你表格的颜色自定义，当前颜色是element默认的颜色
  }

}
::v-deep .el-table__header{
  th:not(.is-hidden):last-child{
    border-left:1px solid #EBEEF5; // 颜色根据你表格的颜色自定义，当前颜色是element默认的颜色
  }
}
::v-deep .el-table th > .cell{
  height: 40px;
  line-height: 40px;

  i{
    color: $text-color-secondary;
    cursor: pointer;
  }
}
::v-deep .el-dialog__header{
  background-color: $bg-color-l2;
  padding-top: 10px;

  .el-dialog__headerbtn{
    top: 0;
  }
}
::v-deep .el-dialog__body{
  padding: 0;
}
::v-deep .el-dialog__footer{
  border-top: 1px solid $color-border-l2;
  padding-bottom: 10px;
}
::v-deep .el-button--text{
  color:$text-color-regular;
}
.operate-primary{
  color:$color-primary;
  font-weight: normal;
}
.operate-danger{
  color:$color-danger;
}

.el-table__row {
  .operate-disabled {
    color: #666 !important;
    cursor: default;
  }
}

.level-padding {
  padding: 0 5px;
}
.qrcode-list-container{
  height: 100%;
  overflow: auto;
  padding: 10px;

  // search
  .qrcode-list-search-group-container {
    background: #fff;
    border-radius: 4px;

    ::v-deep .el-radio-group {
      align-items: center;
      display: flex;
      .el-radio-button__inner {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .advanced-search-function,
    .base-search {
      border-radius: 4px;
    }

    .base-search {
      font-size: 14px;
      display: flex;
      justify-content: space-between;
      // padding: 12px 10px;

      .qrcode-list-base-search-group {
        display: flex;
        min-width: 440px;
        justify-content: space-between;
        align-items: center;

        ::v-deep .el-input {
          height: 32px;
          input {
            height: 32px;
            line-height: 32px;
            width: 100%;
          }
        }
      }

      .advanced-search-visible-btn {
        font-size: 14px;
        line-height: 32px;
        color: $color-primary;
        border-color: $color-primary;
        background: #fff;
        // padding: 0 13px;
        white-space: nowrap;

        &:hover {
          cursor: pointer;
        }

        // .iconfont {
        //   font-weight: bolder;
        // }
      }
    }

    .advanced-search-form {
      overflow: auto;
      padding: 10px 0 63px 0;
      height: calc(100% - 51px);

      .two-columns {
        display: flex;
        flex-wrap: wrap;
        .el-form-item {
          width: 50%;
        }
      }

      .el-form-item {
        .el-form-item__content,
        .el-select,
        .base-dist-picker,
        .el-cascader,
        .el-date-editor {
          width: 290px;
        }
      }

      .advanced-search-btn-group {
        display: flex;
        justify-content: flex-end;
        width: 100%;
        position: absolute;
        bottom: 0px;
        background: #fff;
        padding: 15px 20px;

        .base-button {
          margin: 0 10px;
        }
      }
    }

    .advanced-search-function {
      margin-top: 10px;
      padding-bottom: 10px;

      h4 {
        border-bottom: 1px solid #f4f4f4;
        padding: 10px;
      }

      .el-row {
        padding: 5px 0;
      }
      .input-label {
        text-align: right;
        line-height: 32px;
        padding-right: 0;
      }
    }

    .top-bottom-btns{
      padding: 0 10px 12px;
      display: flex;
      justify-content: space-between;

      a{
        margin-top: 10px;
        color: $color-primary;
      }
    }
  }
  // list
  .qrcode-list-component {
    padding: 0 16px;
    background: #fff;
    margin-top: 12px;
    border-radius: 4px;
    /*min-height: calc(100% - 100px);*/

    .qrcode-table {
      // padding: 16px;
      border: 0;

      &:before {
        height: 0;
      }

      ::v-deep .qrcode-table-header{
        th {
          background: #f5f5f5;
          color: $text-color-primary;
          font-weight: normal;
          height: 40px;
          font-weight: bold;
          padding: 0;
          background: $bg-color-l2;
        }
      }
      ::v-deep .qrcode-table-cell{
        height: 40px;
        padding: 0;
      }

        .view-detail-btn {
          width: 100%;
          color: $color-primary;
        }

      .view-detail-btn {
        color: $color-primary;
      }

      .select-column .el-checkbox {
        position: relative;
        top: 3px;
      }
    }

    .table-footer {
      display: flex;
      justify-content: space-between;
      padding: 0px 10px 10px 10px;
      background: #fff;
      border-radius: 0 0 4px 4px;

      .list-info {
        font-size: 13px;
        line-height: 32px;
        margin: 0;
        color: #767e89;

        .iconfont {
          position: relative;
          top: 1px;
        }
      }

      .el-pagination__jump {
        margin-left: 0;
      }
    }
  }
  .operation-bar-container {
    background: #fff;
    border-radius: 4px 4px 0 0;
    display: flex;
    justify-content: space-between;
    padding-left: 0 !important;
    padding-right: 0 !important;

    .top-btn-group {
      .base-button{
        margin-right: 5px;
      }

      .del-btn{
        padding: 8px 15px;
      }
    }

    .el-dropdown-btn {
      padding: 0 15px;
      line-height: 32px;
      display: inline-block;
      background: $color-primary-light-9;
      color: $text-color-primary;
      outline: none;
      margin-left: 5px;
      .iconfont {
        margin-left: 5px;
        font-size: 12px;
      }

      &:hover {
        cursor: pointer;
        color: #fff;
        background: $color-primary;
      }
    }
  }
}

// -------- customer selected panel --------
.customer-selected-count {
  color: $color-primary;
  padding: 0 3px;
  width: 15px;
  text-align: center;
  cursor: pointer;
  font-size: 13px;
}

.customer-selected-panel {
  font-size: 14px;
  height: calc(100% - 51px);

  .customer-selected-tip {
    padding-top: 80px;

    img {
      display: block;
      width: 240px;
      margin: 0 auto;
    }

    p {
      text-align: center;
      color: #9a9a9a;
      margin: 30px 0 0 0;
      line-height: 20px;
    }
  }

  .customer-selected-list {
    height: 100%;
    padding: 10px;
    overflow-y: auto;

    .customer-selected-row {
      display: flex;
      flex-flow: row nowrap;
      line-height: 36px;
      border-bottom: 1px solid #ebeef5;
      font-size: 13px;

      &:hover {
        background-color: #f5f7fa;

        .customer-selected-delete {
          visibility: visible;
        }
      }
    }

    .customer-selected-head {
      background-color: #f0f5f5;
      color: #333;
      font-size: 14px;
    }

    .customer-selected-sn {
      padding-left: 10px;
      width: 150px;
      @include text-ellipsis;
    }

    .customer-selected-name {
      padding-left: 10px;
      flex: 1;
      @include text-ellipsis;
    }

    .customer-selected-delete {
      width: 36px;
    }

    .customer-selected-row button.customer-selected-delete {
      padding: 0;
      width: 36px;
      height: 36px;
      border: none;
      background-color: transparent;
      outline: none;
      color: #646b78;
      visibility: hidden;

      i {
        font-size: 14px;
      }

      &:hover {
        color: #e84040;
      }
    }
  }
}

// operation
.customer-columns-dropdown-menu {
  max-height: 300px;
  overflow: auto;
  .el-dropdown-menu__item {
    padding: 0;
  }
  .el-checkbox {
    width: 100%;
    padding: 5px 15px;
    margin: 0;
  }
}

.operation-bar-container {
  background: #fff;
  border-radius: 4px 4px 0 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;

  .top-btn-group .base-button {
    margin-right: 5px;
  }

  .action-button-group {
    cursor: pointer;
    .base-button {
      margin-left: 5px;
    }
  }
  .el-dropdown-btn {
    padding: 0 15px;
    line-height: 32px;
    display: inline-block;
    background: $color-primary-light-9;
    color: $text-color-primary;
    outline: none;
    margin-left: 5px;
    .iconfont {
      margin-left: 5px;
      font-size: 12px;
    }

    &:hover {
      cursor: pointer;
      color: #fff;
      background: $color-primary;
    }
  }
}

// superscript
.customer-name-superscript-td {
  padding: 0 !important;
  & > div {
    height: 43px;
    line-height: 43px !important;
    a {
      display: inline-block;
      height: 43px;
      line-height: 43px;
    }
  }
}
.cur-point {
  color: $color-primary-light-6;
}
.lang-select-dropdown {
  margin-top: 0!important;
}
.table-pointer {
  cursor: pointer;
}
</style>
<style lang="scss">
  @import "@src/assets/scss/common-list.scss";
</style>